import os
import shutil

"""
将标注好的子数据集搬移到父数据集，并且重新整理，确保编号正确
（一定要用此py搬移，不然容易出现重命名丢失文件的现象）
"""


def get_highest_numbered_file(directory):
    """获取文件夹中最高编号的文件名"""
    max_number = 0
    for filename in os.listdir(directory):
        try:
            number = int(os.path.splitext(filename)[0])
            if number > max_number:
                max_number = number
        except ValueError:
            continue
    return max_number


def move_and_rename_files_img(src_img_folder, dest_img_folder,src_label_folder,dest_label_folder):
    """将源文件夹中的文件移动到目标文件夹并重新编号"""

    current_number = get_highest_numbered_file(dest_img_folder) + 1

    for filename in os.listdir(src_img_folder):
        file_id,_ = os.path.splitext(filename)
        src_path_img = os.path.join(src_img_folder, file_id+".jpg")
        src_path_label = os.path.join(src_label_folder, file_id+".txt")
        print(src_path_img)
        print(src_path_label)

        if os.path.isfile(src_path_img) and os.path.isfile(src_path_label):
            dest_path_img = os.path.join(dest_img_folder, f"{current_number}.jpg")  
            dest_path_labels = os.path.join(dest_label_folder, f"{current_number}.txt")  
            print(src_path_img, "->", dest_path_img)
            print(src_path_label, "->", dest_path_labels)
            shutil.move(src_path_img, dest_path_img)
            shutil.move(src_path_label, dest_path_labels)
            current_number += 1
    print("文件转移完成，编号已更新。")



# 路径
source_img_folder = "/home/hw/dataset/my_dataset2/images"  # 替换为你的源文件夹路径
destination_img_folder = "/home/hw/dataset/cone_total_new/images"  # 替换为你的目标文件夹路径

source_label_folder = "/home/hw/dataset/my_dataset2/labels"  # 替换为你的源文件夹路径
destination_label_folder = "/home/hw/dataset/cone_total_new/labels"  # 替换为你的目标文件夹路径

move_and_rename_files_img(source_img_folder, destination_img_folder,source_label_folder,destination_label_folder)

